﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExpertMIS.Brokers;
using ExpertMIS.Entities;
using IBatisNet.Common.Utilities;
using System.Data;
using System.Text;
using System.Collections;

namespace ExpertMIS.Forums.UserControl
{
    public partial class ucSearchResult : System.Web.UI.UserControl
    {
        private string _keywords = string.Empty;
        private int _pageSize = 10;
        private bool _showAnswer = true;
        private PagingSize _pagingSize = new PagingSize();
        private AnswerBroker _answerBroker = new AnswerBroker();
        private ADMUserBroker _userBroker = new ADMUserBroker();
        private int _titleLength = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            BuildPagingSize();
        }

        private void BuildPagingSize()
        {
            _pagingSize.Limit = 10;

            int pagingStart = 1;
            if (!int.TryParse(Request["start"], out pagingStart) || pagingStart < 1)
            {
                pagingStart = 1;
            }

            _pagingSize.Start = pagingStart;

            if (!int.TryParse(ExpertMIS.Codes.Utility.GetEnvironmentValue("search.questionlen"), out _titleLength))
            {
                _titleLength = -1;
            }
        }

        protected string HighlightKeywords(string text)
        {
            if (!string.IsNullOrEmpty(_keywords))
            {
                return text.Replace(_keywords, string.Format("<span style='color:red;font-weight:blod;'>{0}</span>", _keywords));
            }
            else
            {
                return text;
            }
        }

        public void SearchByKeywords(string keywords)
        {
            BuildPagingSize();

            _keywords = keywords;
            QuestionBroker broker = new QuestionBroker();

            dlResults.DataSource = broker.SearchQuestionsByKeywords(keywords, _pagingSize);
            dlResults.DataBind();
        }

        public void SearchByAuthor(string authorOID, string keywords)
        {
            BuildPagingSize();

            _keywords = keywords;
            QuestionBroker broker = new QuestionBroker();

            dlResults.DataSource = broker.SearchQuestionsByAuthor(authorOID, keywords, _pagingSize);
            dlResults.DataBind();
        }

        public void SearchToExpert(string expertOID, string keywords)
        {
            BuildPagingSize();

            _keywords = keywords;
            QuestionBroker broker = new QuestionBroker();

            dlResults.DataSource = broker.SearchQuestionsToExpert(expertOID, keywords, _pagingSize);
            dlResults.DataBind();
        }

        public void SearchByReply(string posterOID, string keywords)
        {
            BuildPagingSize();

            _keywords = keywords;
            QuestionBroker broker = new QuestionBroker();

            dlResults.DataSource = broker.SearchQuestionsByAnswerPoster(posterOID, keywords, _pagingSize);
            dlResults.DataBind();
        }

        public bool ShowAnswer
        {
            get { return _showAnswer; }
            set { _showAnswer = value; }
        }

        protected void dlResults_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView row = e.Item.DataItem as DataRowView;

                if (row != null)
                {
                    HyperLink hlQuestion = e.Item.FindControl("hlQuestion") as HyperLink;
                    if (hlQuestion != null)
                    {
                        if (_titleLength > 0)
                        {
                            hlQuestion.Text = HighlightKeywords(ExpertMIS.Codes.Utility.CutLongText(row["F_Title"] != DBNull.Value ? row["F_Title"].ToString() : "", _titleLength));
                        }
                        else
                        {
                            hlQuestion.Text = HighlightKeywords(row["F_Title"] != DBNull.Value ? row["F_Title"].ToString() : "");
                        }
                        hlQuestion.NavigateUrl = string.Format("../QuestionForm.aspx?oid={0}", row["F_OID"] != DBNull.Value ? row["F_OID"].ToString() : "");
                        hlQuestion.Target = "_blank";
                    }

                    Label lblLastAnswer = e.Item.FindControl("lblLastAnswer") as Label;
                    AnswerEntity answer = _answerBroker.GetRecentReply(row["F_OID"].ToString());

                    if (lblLastAnswer != null && answer != null)
                    {
                        ADMUserEntity poster = _userBroker.GetEntityByOID(answer.UserOID);

                        int answerLen = 0;
                        if (!int.TryParse(ExpertMIS.Codes.Utility.GetEnvironmentValue("search.answerlen"), out answerLen))
                        {
                            answerLen = 20;
                        }
                        string answerContext = ExpertMIS.Codes.Utility.CutLongText(answer.Context, answerLen);

                        lblLastAnswer.Text = string.Format(
                            "{0:yy-MM-dd HH:mm:ss}|{1}：{2}",
                            answer.CreateDate,
                            poster != null ? poster.Name : "<span style='color:#CCCCCC;'>该用户已被删除</span>",
                            answerContext);
                    }

                    Label lblPrefix = e.Item.FindControl("lblPrefix") as Label;

                    if (lblPrefix != null)
                    {
                        StringBuilder sbPrefix = new StringBuilder();
                        ADMUserEntity poster = _userBroker.GetEntityByOID(row["F_UserOID"].ToString());

                        sbPrefix.Append(string.Format("<span style='font-size:9pt;color:#6a9fba;'>{0}</span>|", QuestionBroker.TranslateStatus((QuestionStatus)row["F_Status"])));
                        sbPrefix.Append(string.Format("<span style='font-size:9pt;color:#6a9fba;'>回复 {0}</span>|", _answerBroker.GetQuestionAnswerCount(row["F_OID"].ToString())));
                        sbPrefix.Append(string.Format("<span style='font-size:9pt;color:#6a9fba;'>{0}</span>|", ((DateTime)row["F_UpdateDate"]).ToShortDateString()));
                        sbPrefix.Append(string.Format("<span style='font-size:9pt;color:#6a9fba;'>{0}</span>", poster != null ? poster.Name : "<span style='color:#CCCCCC;'>该用户已被删除</span>"));

                        lblPrefix.Text = sbPrefix.ToString();
                    }
                }
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                Panel pnFoo = e.Item.FindControl("pnFoo") as Panel;
                double dbl = (_pageSize - dlResults.Items.Count) * dlResults.ItemStyle.Height.Value;
                if (dbl > 0)
                {
                    pnFoo.Height = new Unit(dbl);
                }
            }
        }

        #region 分页信息

        protected string GetPriorPageIndex()
        {
            if (_pagingSize.Start - 1 > 0)
                return (_pagingSize.Start - 1).ToString();
            else
                return _pagingSize.Start.ToString();
        }

        protected string GetNextPageIndex()
        {
            if (_pagingSize.Start + 1 <= (int)System.Math.Ceiling((double)_pagingSize.Total / _pagingSize.Limit))
                return (_pagingSize.Start + 1).ToString();
            else
                return GetLastPageIndex();
        }

        protected string GetLastPageIndex()
        {
            return ((int)System.Math.Ceiling((double)_pagingSize.Total / _pagingSize.Limit)).ToString();
        }

        protected string GetPageIndex()
        {
            return string.Format("{0}/{1}", _pagingSize.Start, (int)System.Math.Ceiling((double)_pagingSize.Total / _pagingSize.Limit));
        }

        protected string GetRecordCount()
        {
            if (_pagingSize.Total < 0) return "0";
            return _pagingSize.Total.ToString();
        }

        #endregion
    }
}